package com.mofang.ticketing.user.serve.account.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.mofang.ticketing.base.client.api.BaseClient;
import com.mofang.ticketing.base.client.pojo.request.SysConfigGetReqDTO;
import com.mofang.ticketing.common.core.constant.AccountConstant;
import com.mofang.ticketing.common.core.constant.SecurityConstants;
import com.mofang.ticketing.common.core.enums.account.*;
import com.mofang.ticketing.common.core.enums.base.SysEnableEnum;
import com.mofang.ticketing.common.core.exception.BizException;
import com.mofang.ticketing.common.core.result.Result;
import com.mofang.ticketing.common.core.result.ResultCode;
import com.mofang.ticketing.common.core.util.CopyUtil;
import com.mofang.ticketing.common.redis.constant.RedisConstant;
import com.mofang.ticketing.common.redis.service.RedisService;
import com.mofang.ticketing.common.security.bo.RoleInfoBO;
import com.mofang.ticketing.common.security.bo.UserDetailBO;
import com.mofang.ticketing.common.security.bo.UserInfoBO;
import com.mofang.ticketing.common.security.util.JwtTokenUtil;
import com.mofang.ticketing.common.security.util.SecurityUtil;
import com.mofang.ticketing.user.client.pojo.response.AuthUserBelongMerchantRespDTO;
import com.mofang.ticketing.user.mapping.entity.*;
import com.mofang.ticketing.user.mapping.mapper.SysPermissionDOMapper;
import com.mofang.ticketing.user.mapping.mapper.SysRoleDOMapper;
import com.mofang.ticketing.user.mapping.mapper.SysUserDOMapper;
import com.mofang.ticketing.user.mapping.mapper.SysUserRoleDOMapper;
import com.mofang.ticketing.user.serve.account.bo.Actions;
import com.mofang.ticketing.user.serve.account.bo.Children;
import com.mofang.ticketing.user.serve.account.bo.Permission;
import com.mofang.ticketing.user.serve.account.dto.request.AccountLoginReqDTO;
import com.mofang.ticketing.user.serve.account.dto.request.AppendPermissionReqDTO;
import com.mofang.ticketing.user.serve.account.dto.request.InitPlatformAdminAccountReqDTO;
import com.mofang.ticketing.user.serve.account.dto.response.AccountLoinRespDTO;
import com.mofang.ticketing.user.serve.account.dto.response.CurrentAccountInfoRespDTO;
import com.mofang.ticketing.user.serve.account.mapper.AccountMapper;
import com.mofang.ticketing.user.serve.account.service.AuthService;
import com.mofang.ticketing.user.serve.role.mapper.RoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author LGC
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Resource
    private RedisService redisService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private AccountMapper accountMapper;
    @Resource
    private SysUserDOMapper sysUserDOMapper;
    @Resource
    private SysRoleDOMapper sysRoleDOMapper;
    @Resource
    private SysUserRoleDOMapper sysUserRoleDOMapper;
    @Resource
    private SysPermissionDOMapper sysPermissionDOMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private BaseClient baseClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void initializePermission() {
        Result<String> platformAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.PLATFORM_ADMIN.getRoleCode()));
        Result<String> merchantAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.MERCHANT_ADMIN.getRoleCode()));
        Result<String> projectAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.PROJECT_MEMBER.getRoleCode()));
        if (platformAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            if (StrUtil.isNotBlank(platformAdminPermissionResult.getData())) {
                List<Permission> permissions = JSONUtil.toList(platformAdminPermissionResult.getData(), Permission.class);
                insertPermissions(permissions, BelongEnum.PLATFORM.getKey());
            }
        }
        if (merchantAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            if (StrUtil.isNotBlank(merchantAdminPermissionResult.getData())) {
                List<Permission> permissions = JSONUtil.toList(merchantAdminPermissionResult.getData(), Permission.class);
                insertPermissions(permissions, BelongEnum.MERCHANT.getKey());
            }
        }
        if (projectAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            if (StrUtil.isNotBlank(projectAdminPermissionResult.getData())) {
                List<Permission> permissions = JSONUtil.toList(projectAdminPermissionResult.getData(), Permission.class);
                insertPermissions(permissions, BelongEnum.PROJECT_MEMBER.getKey());
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<Permission> appendPermission(AppendPermissionReqDTO dto) {
        List<Permission> permissions = JSONUtil.toList(dto.getAuthority(), Permission.class);
        insertPermissions(permissions, dto.getBelong());
        return permissions;
    }

    private List<Long> insertPermissions(List<Permission> permissions, Integer belong) {
        List<Long> menuAndActionPerList = new ArrayList<>();
        // 权限操作
        SysPermissionDO sysPermissionDO = null;
        for (Permission permission : permissions) {
            sysPermissionDO = new SysPermissionDO(belong, 0L, permission.getTitle(), permission.getPermissionId(), "", SysPerTypeEnum.DIRECTORY.getKey(), 1);
            sysPermissionDOMapper.insert(sysPermissionDO);
            List<Children> children = permission.getChildren();
            if (CollUtil.isNotEmpty(children) && children.size() > 0) {
                Long menuParentId = sysPermissionDO.getId();
                for (Children child : children) {
                    sysPermissionDO = new SysPermissionDO(belong, menuParentId, child.getTitle(), child.getPermissionId(), "", SysPerTypeEnum.MENU.getKey(), 1);
                    sysPermissionDOMapper.insert(sysPermissionDO);
                    menuAndActionPerList.add(sysPermissionDO.getId());
                    List<Actions> actions = child.getActions();
                    if (CollUtil.isNotEmpty(actions) && children.size() > 0) {
                        Long actionParentId = sysPermissionDO.getId();
                        for (Actions action : actions) {
                            sysPermissionDO = new SysPermissionDO(belong, actionParentId, child.getTitle() + "-" + action.getLabel(), action.getPermissionId(), "", SysPerTypeEnum.ACTION.getKey(), 1);
                            sysPermissionDOMapper.insert(sysPermissionDO);
                            menuAndActionPerList.add(sysPermissionDO.getId());
                        }
                    }
                }
            }
        }
        return menuAndActionPerList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserDO initPlatformAdminAccount(InitPlatformAdminAccountReqDTO dto) {
        Result<String> platformAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.PLATFORM_ADMIN.getRoleCode()));
        Result<String> projectAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.PROJECT_MEMBER.getRoleCode()));
        SysUserDO platformAdminAccount = null;
        // 创建平台管理员角色权限
        if (platformAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            SysRoleDO platformAdminRole = new SysRoleDO();
            platformAdminRole.setBelong(BelongEnum.PLATFORM.getKey());
            platformAdminRole.setRoleType(RoleTypeEnum.PLATFORM_ADMIN.getKey());
            platformAdminRole.setRoleName(RoleTypeEnum.PLATFORM_ADMIN.getValue());
            platformAdminRole.setRoleCode(RoleTypeEnum.PLATFORM_ADMIN.getRoleCode());
            platformAdminRole.setIsAdmin(IsAdminEnum.ADMIN.getKey());
            platformAdminRole.setAuthority(platformAdminPermissionResult.getData());
            platformAdminRole.setCreateTime(new Date());
            platformAdminRole.setCreateUserId(0L);
            platformAdminRole.setUpdateTime(new Date());
            platformAdminRole.setUpdateUserId(0L);
            platformAdminRole.setRevision(0);
            sysRoleDOMapper.insert(platformAdminRole);
            List<SysPermissionDO> permissionDOList = new LambdaQueryChainWrapper<>(sysPermissionDOMapper)
                    .eq(SysPermissionDO::getBelong, BelongEnum.PLATFORM.getKey())
                    .eq(SysPermissionDO::getIsEnable, SysEnableEnum.ENABLE.getKey())
                    .in(SysPermissionDO::getType, SysPerTypeEnum.MENU.getKey(), SysPerTypeEnum.ACTION.getKey())
                    .list();
            if (CollUtil.isNotEmpty(permissionDOList)) {
                if (CollUtil.isNotEmpty(permissionDOList)) {
                    Long platformAdminRoleId = platformAdminRole.getId();
                    List<SysRolePermissionDO> insertRolePermissionList = permissionDOList.stream().map(p ->
                            new SysRolePermissionDO(platformAdminRoleId, p.getId())).collect(Collectors.toList());
                    roleMapper.insertRolePermissionBatch(insertRolePermissionList);
                }
            }
            // 创建平台账号
            platformAdminAccount = new SysUserDO();
            platformAdminAccount.setBelong(BelongEnum.PLATFORM.getKey());
            platformAdminAccount.setAccountType(AccountTypeEnum.PLATFORM_ADMIN.getKey());
            platformAdminAccount.setUsername(AccountTypeEnum.PLATFORM_ADMIN.getValue());
            platformAdminAccount.setAccount(dto.getAccount());
            String pwd = StrUtil.isBlank(dto.getPassword()) ? AccountConstant.DEFAULT_PWD : dto.getPassword();
            platformAdminAccount.setPassword(passwordEncoder.encode(pwd));
            platformAdminAccount.setPasswordStrong(AccountConstant.PWD_STRONG);
            platformAdminAccount.setHeadImg(AccountConstant.DEFAULT_HEAD_IMG);
            platformAdminAccount.setIsAdmin(IsAdminEnum.ADMIN.getKey());
            platformAdminAccount.setIsEnable(SysEnableEnum.ENABLE.getKey());
            platformAdminAccount.setCreateTime(new Date());
            platformAdminAccount.setCreateUserId(0L);
            platformAdminAccount.setUpdateTime(new Date());
            platformAdminAccount.setUpdateUserId(0L);
            platformAdminAccount.setRevision(0);
            sysUserDOMapper.insert(platformAdminAccount);

            // 账号绑定为平台管理员角色
            SysUserRoleDO insertUserRole = new SysUserRoleDO(BelongEnum.PLATFORM.getKey(), 0L, platformAdminAccount.getId(), platformAdminRole.getId());
            sysUserRoleDOMapper.insert(insertUserRole);
        }
        // 创建项目成员角色
        if (projectAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            SysRoleDO projectMemberRole = new SysRoleDO();
            projectMemberRole.setBelong(BelongEnum.PROJECT_MEMBER.getKey());
            projectMemberRole.setRoleType(RoleTypeEnum.PROJECT_MEMBER.getKey());
            projectMemberRole.setRoleName(RoleTypeEnum.PROJECT_MEMBER.getValue());
            projectMemberRole.setRoleCode(RoleTypeEnum.PROJECT_MEMBER.getRoleCode());
            projectMemberRole.setIsAdmin(IsAdminEnum.NORMAL.getKey());
            projectMemberRole.setAuthority(projectAdminPermissionResult.getData());
            projectMemberRole.setCreateTime(new Date());
            projectMemberRole.setCreateUserId(0L);
            projectMemberRole.setUpdateTime(new Date());
            projectMemberRole.setUpdateUserId(0L);
            projectMemberRole.setRevision(0);
            sysRoleDOMapper.insert(projectMemberRole);

            List<SysPermissionDO> permissionDOList = new LambdaQueryChainWrapper<>(sysPermissionDOMapper)
                    .eq(SysPermissionDO::getBelong, BelongEnum.PROJECT_MEMBER.getKey())
                    .eq(SysPermissionDO::getIsEnable, SysEnableEnum.ENABLE.getKey())
                    .in(SysPermissionDO::getType, SysPerTypeEnum.MENU.getKey(), SysPerTypeEnum.ACTION.getKey())
                    .list();
            if (CollUtil.isNotEmpty(permissionDOList)) {
                Long projectMemberRoleId = projectMemberRole.getId();
                List<SysRolePermissionDO> insertRolePermissionList = permissionDOList.stream().map(p ->
                        new SysRolePermissionDO(projectMemberRoleId, p.getId())).collect(Collectors.toList());
                roleMapper.insertRolePermissionBatch(insertRolePermissionList);
            }
        }
        return platformAdminAccount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserDO initMerchantAdminAccount(String username, String account, Long merchantId, Long userId) {
        Result<String> merchantAdminPermissionResult = baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.MERCHANT_ADMIN.getRoleCode()));
        // 创建商户管理员角色权限
        SysRoleDO merchantAdminRole = null;
        if (merchantAdminPermissionResult.getCode().equals(ResultCode.SUCCESS.getCode())) {
            merchantAdminRole = new SysRoleDO();
            merchantAdminRole.setBelong(BelongEnum.MERCHANT.getKey());
            merchantAdminRole.setRoleType(RoleTypeEnum.MERCHANT_ADMIN.getKey());
            merchantAdminRole.setRoleName(RoleTypeEnum.MERCHANT_ADMIN.getValue());
            merchantAdminRole.setRoleCode(RoleTypeEnum.MERCHANT_ADMIN.getRoleCode());
            merchantAdminRole.setMerchantId(merchantId);
            merchantAdminRole.setIsAdmin(IsAdminEnum.NORMAL.getKey());
            merchantAdminRole.setAuthority(merchantAdminPermissionResult.getData());
            merchantAdminRole.setCreateTime(new Date());
            merchantAdminRole.setCreateUserId(userId);
            merchantAdminRole.setUpdateTime(new Date());
            merchantAdminRole.setUpdateUserId(userId);
            merchantAdminRole.setRevision(0);
            sysRoleDOMapper.insert(merchantAdminRole);
            List<SysPermissionDO> permissionDOList = new LambdaQueryChainWrapper<>(sysPermissionDOMapper)
                    .eq(SysPermissionDO::getBelong, BelongEnum.MERCHANT.getKey())
                    .eq(SysPermissionDO::getIsEnable, SysEnableEnum.ENABLE.getKey())
                    .in(SysPermissionDO::getType, SysPerTypeEnum.MENU.getKey(), SysPerTypeEnum.ACTION.getKey())
                    .list();
            if (CollUtil.isNotEmpty(permissionDOList)) {
                Long merchantAdminRoleId = merchantAdminRole.getId();
                List<SysRolePermissionDO> insertRolePermissionList = permissionDOList.stream().map(p ->
                        new SysRolePermissionDO(merchantAdminRoleId, p.getId())).collect(Collectors.toList());
                roleMapper.insertRolePermissionBatch(insertRolePermissionList);
            }
        }
        // 创建商户管理员账号
        SysUserDO merchantAdminAccount = insertAccount(BelongEnum.MERCHANT, AccountTypeEnum.MERCHANT_ADMIN, username, account, userId);
        // 绑定账号为商户管理员角色
        sysUserRoleDOMapper.insert(new SysUserRoleDO(BelongEnum.MERCHANT.getKey(), merchantId, merchantAdminAccount.getId(), merchantAdminRole.getId()));
        return merchantAdminAccount;
    }


    @Override
    public AccountLoinRespDTO login(AccountLoginReqDTO dto) {
        String pwdDecrypt = dto.getPassword();
        String account = dto.getAccount();
        // 所属组织
        int belong = 1;
        if (dto.getSource().equals(2)) {
            // 项目成员
            if (account.startsWith(AccountConstant.PROJECT_MEMBER_PREFIX)) {
                belong = 3;
            } else {
                belong = 2;
            }
        }
        UserDetailBO userDetails = getAuthInfo(dto.getAccount(), belong);
        if (userDetails == null || !passwordEncoder.matches(pwdDecrypt, userDetails.getPassword())) {
            throw new BizException(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        }
        if (!userDetails.isEnabled()) {
            throw new BizException(ResultCode.USER_ACCOUNT_LOCKED);
        }
        SecurityUtil.setLoginUser(userDetails);
        String token = jwtTokenUtil.generateToken(userDetails);
        redisService.set(String.format(RedisConstant.LOGIN_INFO_KEY, dto.getAccount()), JSONUtil.toJsonStr(userDetails), SecurityConstants.JWT_EXPIRATION);

        UserInfoBO userInfoBO = userDetails.getUserInfoBO();
        return new AccountLoinRespDTO(token, SecurityConstants.JWT_PREFIX, userInfoBO.getBelong(), userInfoBO.getAccountType(), userInfoBO.getIsAdmin());
    }

    @Override
    public void logout() {
        redisService.del(String.format(RedisConstant.LOGIN_INFO_KEY, SecurityUtil.getAccount()));
        SecurityContextHolder.clearContext();
    }

    @Override
    public CurrentAccountInfoRespDTO currentAccountInfo() {
        CurrentAccountInfoRespDTO accountInfoRespDTO = new CurrentAccountInfoRespDTO();
        UserDetailBO userDetail = SecurityUtil.getLoginUser();
        if (userDetail != null) {
            UserInfoBO userInfoBO = userDetail.getUserInfoBO();
            BeanUtil.copyProperties(userInfoBO, accountInfoRespDTO);
            accountInfoRespDTO.setUserId(userInfoBO.getId());

            List<RoleInfoBO> roleList = userDetail.getRoleList();
            if (CollectionUtils.isNotEmpty(roleList)) {
                RoleInfoBO roleInfoBO = roleList.get(0);
                accountInfoRespDTO.setRoleId(roleInfoBO.getId());
                accountInfoRespDTO.setRoleName(roleInfoBO.getRoleName());
                accountInfoRespDTO.setRoleCode(roleInfoBO.getRoleCode());
                accountInfoRespDTO.setAuthority(roleInfoBO.getAuthority());
            }
            userDetail.setPerms(userDetail.getPerms());
        }
        baseClient.configGet(new SysConfigGetReqDTO(RoleTypeEnum.PLATFORM_ADMIN.getRoleCode()));
        return accountInfoRespDTO;
    }


    @Override
    public UserDetailBO getAuthInfo(String account, Integer belong) {
        List<SysRoleDO> roleList = new ArrayList<>();
        Set<String> roleCodeSet = new HashSet<>();
        Set<String> perKeySet = new HashSet<>();
        SysUserDO sysUserDO = accountMapper.selectUserByAccountAndBelong(account, belong);
        if (sysUserDO != null) {
            Set<Long> roleIdSet = new LambdaQueryChainWrapper<>(sysUserRoleDOMapper)
                    .eq(SysUserRoleDO::getUserId, sysUserDO.getId()).list()
                    .stream().map(SysUserRoleDO::getRoleId).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(roleIdSet)) {
                List<SysRoleDO> sysRoleList = sysRoleDOMapper.selectBatchIds(roleIdSet);
                if (CollectionUtils.isNotEmpty(sysRoleList)) {
                    for (SysRoleDO sysRoleDO : sysRoleList) {
                        roleList.add(SysRoleDO.builder()
                                .id(sysRoleDO.getId())
                                .roleName(sysRoleDO.getRoleName())
                                .roleCode(SecurityConstants.AUTHORITY_PREFIX + sysRoleDO.getRoleCode())
                                .authority(sysRoleDO.getAuthority())
                                .isAdmin(sysRoleDO.getIsAdmin())
                                .build());
                    }
                }
            }

            roleCodeSet = roleList.stream().map(SysRoleDO::getRoleCode).collect(Collectors.toSet());
            perKeySet = accountMapper.selectPerKeyByRoleId(roleIdSet);

            return new UserDetailBO(CopyUtil.copy(sysUserDO, UserInfoBO.class), CopyUtil.copyList(roleList, RoleInfoBO.class), roleCodeSet, perKeySet);
        }

        throw new BizException(ResultCode.USERNAME_OR_PASSWORD_ERROR);
    }

    @Override
    public List<AuthUserBelongMerchantRespDTO> authBelongMerchants() {
        return CopyUtil.copyList(accountMapper.selectUserBelongMerchant(SecurityUtil.getUserId(), null), AuthUserBelongMerchantRespDTO.class);
    }

    @Override
    public List<Long> authBelongMerchantIds() {
        return authBelongMerchants().stream().map(AuthUserBelongMerchantRespDTO::getId).collect(Collectors.toList());
    }

    /**
     * 更新账号密码
     *
     * @param sysUserDO
     * @param confirmPwd
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAccountPwd(SysUserDO sysUserDO, String confirmPwd) {
        return new LambdaUpdateChainWrapper<>(sysUserDOMapper)
                .set(SysUserDO::getPassword, passwordEncoder.encode(confirmPwd))
                .set(SysUserDO::getPasswordStrong, AccountConstant.PWD_STRONG)
                .set(SysUserDO::getUpdateUserId, SecurityUtil.getUserId())
                .set(SysUserDO::getUpdateTime, new Date())
                .set(SysUserDO::getRevision, sysUserDO.getRevision() + 1)
                .eq(SysUserDO::getId, sysUserDO.getId())
                .eq(SysUserDO::getRevision, sysUserDO.getRevision()).update();
    }

    /**
     * 更新账号（手机号）
     *
     * @param sysUserDO
     * @param newPhone
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateAccount(SysUserDO sysUserDO, String newPhone) {
        return new LambdaUpdateChainWrapper<>(sysUserDOMapper)
                .set(SysUserDO::getAccount, newPhone)
                .set(SysUserDO::getUpdateUserId, SecurityUtil.getUserId())
                .set(SysUserDO::getUpdateTime, new Date())
                .set(SysUserDO::getRevision, sysUserDO.getRevision() + 1)
                .eq(SysUserDO::getId, sysUserDO.getId())
                .eq(SysUserDO::getRevision, sysUserDO.getRevision()).update();
    }

    /**
     * 更新用户名
     *
     * @param username
     * @param sysUserDO
     */
    @Override
    public boolean updateUsername(String username, SysUserDO sysUserDO) {
        return new LambdaUpdateChainWrapper<>(sysUserDOMapper)
                .set(SysUserDO::getUsername, username)
                .set(SysUserDO::getUpdateUserId, SecurityUtil.getUserId())
                .set(SysUserDO::getUpdateTime, new Date())
                .set(SysUserDO::getRevision, sysUserDO.getRevision() + 1)
                .eq(SysUserDO::getId, sysUserDO.getId())
                .eq(SysUserDO::getRevision, sysUserDO.getRevision()).update();
    }

    /**
     * 账号禁用启用
     *
     * @param sysUserDO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean accountEnable(SysUserDO sysUserDO) {
        return new LambdaUpdateChainWrapper<>(sysUserDOMapper)
                .set(SysUserDO::getIsEnable, sysUserDO.getIsEnable().equals(SysEnableEnum.ENABLE.getKey()) ? SysEnableEnum.DISABLE.getKey() : SysEnableEnum.ENABLE.getKey())
                .set(SysUserDO::getUpdateUserId, SecurityUtil.getUserId())
                .set(SysUserDO::getUpdateTime, new Date())
                .set(SysUserDO::getRevision, sysUserDO.getRevision() + 1)
                .eq(SysUserDO::getId, sysUserDO.getId())
                .eq(SysUserDO::getRevision, sysUserDO.getRevision()).update();
    }

    /**
     * 插入用户
     *
     * @param belongEnum
     * @param accountTypeEnum
     * @param username
     * @param account
     * @param userId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public SysUserDO insertAccount(BelongEnum belongEnum, AccountTypeEnum accountTypeEnum, String username, String account, Long userId) {
        SysUserDO insertAccount = new SysUserDO();
        insertAccount.setBelong(belongEnum.getKey());
        insertAccount.setAccountType(accountTypeEnum.getKey());
        insertAccount.setUsername(username);
        insertAccount.setAccount(account);
        insertAccount.setPassword(passwordEncoder.encode(AccountConstant.DEFAULT_PWD));
        insertAccount.setPasswordStrong(AccountConstant.PWD_STRONG);
        insertAccount.setHeadImg(AccountConstant.DEFAULT_HEAD_IMG);
        insertAccount.setIsEnable(SysEnableEnum.ENABLE.getKey());
        insertAccount.setIsAdmin(IsAdminEnum.NORMAL.getKey());
        insertAccount.setCreateUserId(userId);
        insertAccount.setCreateTime(new Date());
        insertAccount.setUpdateUserId(userId);
        insertAccount.setUpdateTime(new Date());
        insertAccount.setRevision(0);
        sysUserDOMapper.insert(insertAccount);
        return insertAccount;
    }
}
